﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PiaoanWeb.AppLogic.DataAccessLayer;
namespace PiaoanWeb.AppLogic.BusinessLogicLayer
{
    [System.ComponentModel.DataObject(true)]
    public class ProductsBLL : IDisposable
    {
        DatabaseContext _DatabaseContext;
        public ProductsBLL():this(new DatabaseContext())
        { 
        }

        public ProductsBLL(DatabaseContext DatabaseContext)
        {
            _DatabaseContext = DatabaseContext;
        }

        public void Dispose()
        {
            if (_DatabaseContext != null)
            {
                _DatabaseContext.Dispose();
                _DatabaseContext = null;
            }

            GC.SuppressFinalize(this);
        }

        public void AddProduct(Products newProduct)
        {
            _DatabaseContext.Products.Add(newProduct);
            _DatabaseContext.SaveChanges();
        }

        public List<Products> GetAllProducts()
        {
            return _DatabaseContext.Products.Where(p=>!p.IsDeleted).ToList();
        }

        public Products GetProductByID(int productID)
        {
            return _DatabaseContext.Products.Where(p => p.ID == productID).FirstOrDefault();
        }

        public void Save()
        {
            _DatabaseContext.SaveChanges();
        }

        public void DeleteProductsByID(int productID)
        {
            Products product = _DatabaseContext.Products.Where(p => p.ID == productID).FirstOrDefault();
            _DatabaseContext.Products.Remove(product);
            _DatabaseContext.SaveChanges();
        }

        public List<Products> GetLatestProducts()
        {
            return _DatabaseContext.Products.Where(p => !p.IsDeleted && !p.ProductImage.ToLower().Equals("noimage.jpg")).OrderByDescending(p => p.ID).Take(10).ToList();
        }

        public List<Products> GetProductsByCategoryID(int categoryID)
        {
            if (categoryID == 0)
            {
                return _DatabaseContext.Products.Where(p => !p.IsDeleted && !p.ProductImage.ToLower().Equals("noimage.jpg")).ToList();
            }
            else
            {
                return _DatabaseContext.Products.Where(p => !p.IsDeleted && !p.ProductImage.ToLower().Equals("noimage.jpg") && p.CategoryID == categoryID).ToList();
            }
        }
    }
}